/**
 * 导入组件
 */
import React, { ReactElement } from "react";
import {
  Button,
  Space,
  PageHeader,
  Steps,
  message,
  Upload,
  Tooltip,
  Row,
  Col,
} from "antd";
import {
  UploadOutlined,
  FileExcelOutlined,
  CheckOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import uniqid from "uniqid";
import XLSX from "xlsx";
import "./ImportExportExcel.css";

const { Dragger } = Upload;
const { Step } = Steps;
interface Props {
  handleCancelImport?: any;
  importTitle: string;
  importColums: any;
}

export default function ImportExportExcel(props: Props): ReactElement {
  const [current, setCurrent] = React.useState(0);
  const [tableData, setTableData] = React.useState<any[]>([]);

  const importColumns = props.importColums;

  /**
   * 下一步骤
   */
  const next = () => {
    setCurrent(current + 1);
  };

  //导入配置项
  const uploadProps = {
    accept: ".xls,.xlsx,application/vnd.ms-excel",
    name: "file",
    action:
      "http://iwmsts.timeexpress.com.cn:8080/iwms-account/account/oss/upload",
    beforeUpload: (file: any) => {
      const f = file;
      console.log(f);
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const datas = e.target.result;
        const workbook = XLSX.read(datas, {
          type: "binary",
        });
        const first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonArr = XLSX.utils.sheet_to_json(first_worksheet, {
          header: 1,
        });
        handleImpotedJson(jsonArr, file);
      };
      reader.readAsBinaryString(f);
      return false;
    },
    onChange(info: any) {
      const { status } = info.file;
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (status === "done") {
        message.success(`${info.file.name} file uploaded successfully.`);
      } else if (status === "error") {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

  /**
   * 处理导入的数据
   * @param jsonArr
   * @param file
   */
  const handleImpotedJson = (jsonArr: any, file: any) => {
    jsonArr.splice(0, 1); // 去掉表头
    console.log(jsonArr);
    const jsonArrData = jsonArr.map((item: any, index: number) => {
      let jsonObj: any = {};
      jsonObj.index = index + 1;
      jsonObj.key = "user-wage-" + index;

      item.forEach((im: any, i: number) => {
        jsonObj[importColumns[i].dataIndex] = im;
      });
      return jsonObj;
    });
    console.log(jsonArrData);
    setTableData(jsonArrData);
  };

  //进度项
  const steps = [
    {
      title: "选择导入文件",
      content: (
        <div className="excel-import-index-select">
          <div className="antd-pro-components-excel-import-index-downloadTemplate">
            <span className="antd-pro-components-excel-import-index-badge ant-badge ant-badge-status ant-badge-not-a-wrapper">
              <span className="ant-badge-status-dot ant-badge-status-processing"></span>
              <span className="ant-badge-status-text"></span>
            </span>
            <span>导入文件具体格式规范，请下载模板进行参考</span>
            <button
              type="button"
              className="ant-btn excel-import-index-downloadBtn ant-btn-primary"
            >
              <span>下载模板</span>
            </button>
          </div>
          <div className="excel-import-index-upload">
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">将文件拖至此处或者点击上传文件</p>
              <p className="ant-upload-hint">
                支持xls、xlsx格式文件，建议上传文件大小不超过1M
              </p>
            </Dragger>
            <Row justify="center" style={{ marginTop: "20px" }}>
              <Col span={4}>
                <button
                  type="button"
                  className="ant-btn ant-btn-primary ant-btn-background-ghost"
                  style={{ textAlign: "center" }}
                  onClick={next}
                >
                  <span>下一步</span>
                </button>
              </Col>
            </Row>
          </div>

          <div className="excel-import-index-tips">
            <span>提示:</span>
            <br />
            <Tooltip title="prompt text">
              <span>1. 建议条数≤1000条，条数过多可分批次导入；</span>
              <br />
              <span>2. 模板中列标题为红色的是必填项；</span>
              <br />
              <span>
                3. 选择文件后即在后端进行缓存，点击下一步进行批量导入；
              </span>
              <br />
              <span>
                4.
                若批量导入有数据导入失败，可以下载具体导入失败数据（包括导入失败原因）
              </span>
            </Tooltip>
          </div>
        </div>
      ),
    },
    {
      title: "导入结果",
      content: (
        <div className="excel-import-index-result">
          <div className="excel-import-index-fileName">
            <FileExcelOutlined
              style={{ color: "rgb(59, 119, 227)", fontSize: "24px" }}
            />
            <span style={{ fontSize: "18px", marginLeft: "10px" }}>
              供应商导入模板.xlsx
            </span>
          </div>
          <div className="excel-import-index-report">
            <span>导入情况：</span>
            <div className="excel-import-index-detail">
              <span>
                <CheckOutlined style={{color:'green'}}/>
                成功0条
              </span><br/>
              <span>
                <CloseOutlined style={{color:'red'}}/>
                失败5条
              </span>
            </div>
          </div>
          <div className="excel-import-index-operate">
            <Button type="primary" className="ant-btn-background-ghost" style={{display:'block'}}>下载失败</Button><br/>
            <Button type="primary">继续导入</Button>
          </div>
        </div>
      ),
    },
  ];

  console.log(tableData);

  return (
    <div key={uniqid()}>
      <PageHeader
        key={uniqid()}
        backIcon={false}
        ghost={false}
        onBack={() => window.history.back()}
        title={props.importTitle}
        extra={[
          <Space>
            <Button onClick={props.handleCancelImport}>返回</Button>
          </Space>,
        ]}
      ></PageHeader>
      <div style={{ backgroundColor: "white", marginTop: "8px" }}>
        <div
          style={{ maxWidth: "700px", margin: "0 auto", paddingTop: "50px" }}
        >
          <Steps current={current}>
            {steps.map((item) => (
              <Step key={item.title} title={item.title} />
            ))}
          </Steps>
          <div className="steps-content">{steps[current].content}</div>
        </div>
      </div>
    </div>
  );
}
